#include    "errorpage.h"
#include    "../utils/os.h"

#include    <cstdio>
#include    <microhttpd.h>

ErrorPage & ErrorPage::Instance() {
    static ErrorPage * g_pages = new ErrorPage();
    return *g_pages;
}

void ErrorPage::Set(int err_code, const std::string & page) {
    if (!Exists(page.c_str())) return;

    FILE * file = fopen(page.c_str(), "r");
    if (!file) return;

    std::string content;
    content.reserve(65536);

    char buf[1024] = {0};
    
    do {
        size_t readed = fread(buf, 1, 1024, file);
        if (readed > 0) content.append(buf, readed);
    } while (!feof(file));

    fclose(file);
    _pages[err_code] = content;
}

#define CSS_CODE(code) #code

const std::string & ErrorPage::Get(int err_code) {
    auto it = _pages.find(err_code);
    if (it == _pages.end()) {
        std::string page;
        
        page.append(CSS_CODE(
            <style>
            .content {
                text-align: center;
                margin-top: 15%;
            }
            .errcode {
                font-family: Courier;
                font-size: 4em;
                margin-right: 32px;
            }
            .errmsg {
                font-family: Courier;
                font-size: 3.2em;
                text-transform: uppercase;
            }
            .linkbtn {
                margin-top: 16px;
                font-size: 1.5em;
                cursor: pointer;
                color: rgb(59,59,59);
                font-weight: 400;
                background-color: transparent;
                text-decoration: none;
                text-align: center;
            }
            .linkbtn:hover {
                color: #10af88;
                cursor: pointer;
                text-decoration: none;
            }
            </style>
        ));

        page.append("<div class='content'><span><label class='errcode'>:( " + std::to_string(err_code));
        page.append("</label><small class='errmsg'>");
        page.append(MHD_get_reason_phrase_for(err_code));
        page.append("</small></span><hr style='margin-bottom: 32px;'>");
        page.append("<a href='/' class='linkbtn'>");
        page.append("<svg xmlns='http://www.w3.org/2000/svg' width='.7em' height='.7em' viewbox='0 0 8 8'><path d='M4 0c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 1v2h3v2h-3v2l-3-3 3-3z' /></svg>&nbsp;");
        page.append("GO BACK HOME</a></div>");

        _pages[err_code] = page;
        return _pages[err_code];
    } else {
        return it->second;
    }
}

#undef CSS_CODE